import { useState } from "react";

function Square({ value, onSquareClick, classNames }) {
    // console.log(classNames);
    return <button className={`border border-indigo-600 w-16 h-16 text-center text-4xl font-bold ${classNames}`} onClick={onSquareClick}>{value}</button>;
}

function calculateWinner(squares) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];
    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return {
                winner: squares[a],
                lines: [a, b, c]
            };
        }
    }
    return null;
}

function Board({ xIsNext, squares, onPlay }) {
    // const [squares, setSquares] = useState(Array(9).fill(null));
    // const [xIsNext, setXIsNext] = useState(true);
    const handleClick = (index) => {
        if (squares[index] || calculateWinner(squares)) return;
        const newSquares = squares.slice();
        if (xIsNext) newSquares[index] = 'X';
        else newSquares[index] = 'O';
        // setSquares(newSquares);
        // setXIsNext(!xIsNext);
        onPlay(newSquares)
    }
    const winner = calculateWinner(squares);
    const status = winner?.winner ? `胜利者: ${winner.winner}` : `轮到: ${xIsNext ? 'X' : 'O'} `;
    const SquareList = () => {
        return squares.map((value, index) => <Square key={index} value={value} onSquareClick={() => handleClick(index)} classNames={ winner?.lines.includes(index) ? 'bg-indigo-600 text-white' : '' } />);
    }
    return (
        <>
            <div className="flex flex-col items-start">
                <div className="text-center text-2xl font-bold mb-4">{status}</div>
                <div className="grid grid-cols-3 gap-1 w-[12.5rem]" >
                    <SquareList />
                </div>
            </div>
        </>
    );
}

export default function Game() {
    const [history, setHistory] = useState([Array(9).fill(null)]);
    const [currentMove, setCurrentMove] = useState(0);
    const currentSquares = history[currentMove];
    const handleClick = (nextSquares) => {
        const nextList = [...history.slice(0, currentMove + 1), nextSquares];
        setHistory(nextList);
        setCurrentMove(nextList.length - 1);
    }
    const moves = history.map((squares, move) => {
        return (
            <li key={move} onClick={() => setCurrentMove(move)} className="w-40">
                <button>{move ? `第 #${move} 步` : '初始'}</button>
            </li>
        )
    })
    return (
        <div className="flex">
            <Board xIsNext={(currentMove % 2) === 0} squares={currentSquares} onPlay={handleClick} />
            <div className="ml-8">
                <ol>{moves}</ol>
            </div>
        </div>
    )
}